package com.shujia.flink.state;

import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.connector.base.DeliveryGuarantee;
import org.apache.flink.connector.kafka.sink.KafkaRecordSerializationSchema;
import org.apache.flink.connector.kafka.sink.KafkaSink;
import org.apache.flink.connector.kafka.source.KafkaSource;
import org.apache.flink.connector.kafka.source.enumerator.initializer.OffsetsInitializer;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.util.Properties;

public class Demo4FlinkOnKafkaExactlyOnce {
    public static void main(String[] args) throws Exception {
        //1、创建flink的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //创建kafka source
        KafkaSource<String> source = KafkaSource.<String>builder()
                .setBootstrapServers("master:9092,node1:9092,node2:9092")//broker列表
                .setTopics("test1")//指定topic
                .setGroupId("Demo4KafkaSource")//消费者组，一条数据在一个组内只消费一次
                .setStartingOffsets(OffsetsInitializer.earliest())//earliest: 从最早开始消费，latest：从最新开始消费
                .setValueOnlyDeserializer(new SimpleStringSchema())//指定读取数据的格式
                .build();

        //使用kafka source
        DataStream<String> linesDS = env.fromSource(source, WatermarkStrategy.noWatermarks(), "Kafka Source");

        DataStream<String> filterDS = linesDS.filter(word -> !"null".equals(word));


        Properties properties = new Properties();
        //指定事务超时时间。要比15分钟小
        properties.setProperty("transaction.timeout.ms", 10 * 60 * 1000 + "");

        //将结果保存到kafka中
        KafkaSink<String> sink = KafkaSink.<String>builder()
                .setBootstrapServers("master:9092,node1:9092,node2:9092")//broker列表
                .setKafkaProducerConfig(properties)
                .setRecordSerializer(KafkaRecordSerializationSchema.builder()
                        .setTopic("test3")//指定topic
                        .setValueSerializationSchema(new SimpleStringSchema())//指定数据格式
                        .build()
                )
                //指定数据处理的语义AT_LEAST_ONCE：至少一次，EXACTLY_ONCE：唯一一次
                .setDeliverGuarantee(DeliveryGuarantee.EXACTLY_ONCE)
                .build();

        filterDS.sinkTo(sink);

        env.execute();

    }
}
